#!/bin/bash

port=1025
start_port=$port

ipAddress=xx.xx.xx.xx
managementIpAddress=xx.xx.xx.xx
worldSize=2
modelWeightPath="/data01/nlp/Qwen25-32B-Instruct"
modelName="Qwen25-32B-Instruct"
multiNodesInferEnabled=false
httpsEnabled=false

jq --arg ipAddress "$ipAddress" --arg managementIpAddress "$managementIpAddress"  --argjson worldSize $worldSize --arg modelWeightPath "$modelWeightPath" --arg modelName "$modelName" --argjson multiNodesInferEnabled $multiNodesInferEnabled  --argjson httpsEnabled  $httpsEnabled \
'.ServerConfig.ipAddress = $ipAddress | .ServerConfig.managementIpAddress = $managementIpAddress | .BackendConfig.ModelDeployConfig.ModelConfig[0].worldSize = $worldSize | .BackendConfig.ModelDeployConfig.ModelConfig[0].modelWeightPath = $modelWeightPath | .BackendConfig.ModelDeployConfig.ModelConfig[0].modelName = $modelName | .BackendConfig.multiNodesInferEnabled = $multiNodesInferEnabled | .ServerConfig.httpsEnabled = $httpsEnabled' /usr/local/Ascend/mindie/latest/mindie-service/conf/config.json > tmp.$$.json && mv tmp.$$.json /usr/local/Ascend/mindie/latest/mindie-service/conf/config.json

num_services=$((8 / worldSize))

for index in $(seq 1 $num_services); do
    start_device_id=$(( (index - 1) * worldSize ))
    npuDeviceIds=$(seq -s, $start_device_id $((start_device_id + worldSize - 1)))
    echo "${ipAddress}:${port} 使用设备:${npuDeviceIds}"
    jq --argjson port $port --argjson managementPort $(($port + 1)) --argjson metricsPort $(($port + 2)) --argjson npuDeviceIds "[[$npuDeviceIds]]" \
    '.ServerConfig.port = $port | .ServerConfig.managementPort = $managementPort | .ServerConfig.metricsPort = $metricsPort | .BackendConfig.npuDeviceIds = $npuDeviceIds' /usr/local/Ascend/mindie/latest/mindie-service/conf/config.json > tmp.$$.json && mv tmp.$$.json /usr/local/Ascend/mindie/latest/mindie-service/conf/config.json
    chmod 640 /usr/local/Ascend/mindie/latest/mindie-service/conf/config.json
    if [ ! -d "./qwen_logs" ]; then
        mkdir ./qwen_logs
    fi
    log_file="./qwen_logs/${index}_log.log"

    /usr/local/Ascend/mindie/latest/mindie-service/bin/mindieservice_daemon > "$log_file" 2>&1 &
    daemon_pid=$!

    while true; do
        if grep -q "Daemon start success" "$log_file"; then
            echo "${ipAddress}:${port} 服务启动成功!"
            break
        elif grep -q "kill" "$log_file"; then
            echo "检测到 'kill' 信号，退出循环。"
            exit 1
	elif ! kill -0 $daemon_pid 2>/dev/null; then
	    echo "进程 ${daemon_pid} 终止。请查看日志文件: $log_file"
	    exit 1
        fi
        sleep 1
    done
    
    
    port=$(($port + 100))
done